package com.hangzhou.xyj.ui.activity.base;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hangzhou.xyj.R;
import com.hangzhou.xyj.XYJApplication;
import com.hangzhou.xyj.db.preferences.CommonPreferences;
import com.hangzhou.xyj.manager.IntentManager;
import com.hangzhou.xyj.manager.ScreenManager;
import com.hangzhou.xyj.net.listener.HttpResponseListener;
import com.hangzhou.xyj.ui.dialog.LoadingDialog;
import com.hangzhou.xyj.ui.widget.CommonTitleBarView;
import com.hangzhou.xyj.ui.widget.CommonTitleBarView.OnBackListener;
import com.hangzhou.xyj.ui.widget.CommonTitleBarView.OnNavRightListener;
import com.hangzhou.xyj.ui.widget.CommonTitleBarView.OnTitleListener;
import com.hangzhou.xyj.ui.widget.views.MyTextView;
import com.hangzhou.xyj.utils.EventBusUtil;
import com.hangzhou.xyj.utils.StringUtil;
import com.hangzhou.xyj.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;


/**
 * Created by neo.duan on 2015/12/20.
 * 所有Activity的基类
 */
public abstract class BaseActivity extends FragmentActivity {

    public final String TAG = getClass().getSimpleName();
    public Context mContext;
    protected int mMyUserId;//用户Id
    protected CommonTitleBarView mLlTop;
    private SwipeRefreshLayout mRefreshLayout;
    private View mContentView;
    private TextView mTvFailure;
    private boolean mErrorViewEnable = true; //错误页面是否可用
    private LoadingDialog mLoadingDialog;
    private MyTextView mTvNoDataTip;//没有数据的时候 提示文本

    private RelativeLayout mRlLoadingAnim;//加载动画区域
    private ImageView mIvLoadingAnim;//动画
    private AnimationDrawable animation;
    private boolean isLoadingAnimShow;//加载动画是否可见

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.activity_base);

        mContext = this;
        if (StringUtil.isNotEmpty(CommonPreferences.getUserId(mContext))) {
            mMyUserId = Integer.valueOf(CommonPreferences.getUserId(mContext));
        }


        //用堆栈管理Activity
        ScreenManager.getInstance().pushActivity(this);

        initBaseView();
        initBaseListeners();

        /***初始化intent传递的数据****/
        if (getIntent() != null) {
            initIntentData(getIntent());
        }
        /***初始化标题栏****/
        initTop();
        /***初始化内容布局****/
        initLayouts();
        /***初始化内容view****/
        initViews();
        /***初始化事件监听****/
        initListeners();
        /***初始化数据****/
        initDatas();
    }

    /**
     * 初始化intent传递的数据
     */
    public void initIntentData(Intent intent) {

    }

    /**
     * 设置没有数据的时候 提示文本
     *
     * @param
     * @return
     * @author yaohuix
     * @date 2016/4/25 16:00
     */
    public void setNoDataTip(boolean enable, String text) {
        if (enable) {
            mTvNoDataTip.setText(text.trim());
            mTvNoDataTip.setVisibility(View.VISIBLE);
        } else {
            mTvNoDataTip.setVisibility(View.GONE);
        }
    }

    protected void setLoadingAnimVisible(boolean animVisible) {
        animation = (AnimationDrawable) mIvLoadingAnim.getBackground();
        if (animVisible) {
            mRlLoadingAnim.setVisibility(View.VISIBLE);
            animation.start();
            isLoadingAnimShow = true;
        } else {
            mRlLoadingAnim.setVisibility(View.GONE);
            animation.stop();
            isLoadingAnimShow = false;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (animation != null && animation.isRunning()) {//销毁动画
            animation.stop();
        }
    }

    /**
     * 基类View初始化
     */
    private void initBaseView() {
        mLlTop = findView(R.id.title_id_root);
        mRlLoadingAnim = findView(R.id.rl_loading_anim);
        mRefreshLayout = findView(R.id.content_id_root);
        mTvFailure = findView(R.id.content_id_failure);
        mTvNoDataTip = findView(R.id.mtv_nodata_tip);
        mIvLoadingAnim = findView(R.id.iv_loading_anim);
        //设置默认下拉刷新不可用
        mRefreshLayout.setEnabled(false);
    }

    /**
     * 初始化基类事件
     */
    protected void initBaseListeners() {
        mLlTop.setOnBackListener(new OnBackListener() {

            @Override
            public void onBack() {
                onBackClick();
            }
        });
        //下拉刷新
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                doRefresh();
            }
        });
        //点击重试
        mTvFailure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doRefresh();
            }
        });
    }

    /**
     * 重新加载：默认initData,如果不需要initData，可以重写该方法
     */
    public void doRefresh() {
        initDatas();
    }

    /**
     * 默认返回键处理
     */
    private void onBackClick() {
        closeActivity();
    }

    @Override
    public void setContentView(int layoutResID) {
        mContentView = View.inflate(this, layoutResID, null);
        mRefreshLayout.addView(mContentView);
    }

    /**
     * 获取内容布局
     *
     * @return
     */
    public View getContentView() {
        return mContentView;
    }

    @Override
    public void setContentView(View contentView) {
        this.mContentView = contentView;
        mRefreshLayout.addView(mContentView);
    }

    /**
     * 获取顶部标题栏
     *
     * @return
     */
    public CommonTitleBarView getTopBar() {
        return mLlTop;
    }

    /**
     * 是否显示顶部导航
     *
     * @param enabled
     */
    public void enableTop(boolean enabled) {
        mLlTop.setVisibility(enabled ? View.VISIBLE : View.GONE);
    }


    /**
     * 是否显示左导航键
     *
     * @param enabled
     */
    public void enableBack(boolean enabled) {
        mLlTop.enableBack(enabled);
    }

    public void enableBack(boolean enabled, Drawable drawable) {
        mLlTop.enableBack(enabled, drawable);
    }

    public void enableBack(boolean enabled, int resId) {
        mLlTop.enableBack(enabled, resId);
    }

    public void enableBack(boolean enabled, View view) {
        mLlTop.enableBack(enabled, view);
    }

    public void enableRightNav(boolean enabled) {
        mLlTop.enableRightNav(enabled);
    }

    public void enableRightNav(boolean enabled, int resId) {
        mLlTop.enableRightNav(enabled, resId);
    }

    public void enableRightNav(boolean enabled, String rightNav) {
        mLlTop.enableRightNav(enabled, rightNav);
    }

    public void enableRightNavTwoImg(boolean enabled, Drawable img1Drawable, Drawable img2Drawable) {
        mLlTop.enableRightNavTwoImg(enabled, img1Drawable, img2Drawable);
    }

    /**
     * 设置标题
     *
     * @param enabled
     * @param title
     */
    public void enableTitle(boolean enabled, String title) {
        mLlTop.enableTitle(enabled, title);
    }

    /**
     * 设置顶部标题栏背景颜色
     *
     * @param resId
     */
    public void setTopBarBackground(int resId) {
        if (resId < 0) {
            return;
        }
        mLlTop.setBackgroundColor(getResources().getColor(resId));
    }

    /**
     * 下拉刷新是否可用
     *
     * @param enabled
     */
    public void enableRefresh(boolean enabled) {
        mRefreshLayout.setEnabled(enabled);
    }

    /**
     * 是否显示网络错误页面
     *
     * @param enable
     */
    public void enableNetErrorView(boolean enable) {
        this.mErrorViewEnable = enable;
        mTvFailure.setEnabled(enable);
    }

    /**
     * 显示网络错误View
     */
    private void showNetErrorView(boolean show) {
        //设置了网络错误页面不可用，do nothing
        if (!mErrorViewEnable) {
            return;
        }
        mTvFailure.setVisibility(show ? View.VISIBLE : View.GONE);
        mRefreshLayout.setVisibility(show ? View.GONE : View.VISIBLE);
    }

    public abstract void initTop();

    /**
     * 初始化视图
     */
    public abstract void initLayouts();

    /**
     * 初始化视图
     */
    public abstract void initViews();

    /**
     * 初始化数据
     */
    public abstract void initDatas();

    /**
     * 初始化监听器
     */
    public abstract void initListeners();

    /**
     * 设置左导航事件
     *
     * @param listener
     */
    public void setOnBackListener(OnBackListener listener) {
        mLlTop.setOnBackListener(listener);
    }

    /**
     * 设置右导航事件
     *
     * @param listener
     */
    public void setOnNavRightListener(OnNavRightListener listener) {
        mLlTop.setOnNavRightListener(listener);
    }

    /**
     * 设置右导航2张图片的时候 左边图片的事件
     *
     * @param listener
     */
    public void setOnNavRightLeftImgListener(CommonTitleBarView.OnNavRightLeftImgListener listener) {
        mLlTop.setOnNavRightLeftImgListener(listener);
    }

    /**
     * 设置标题事件
     *
     * @param listener
     */
    public void setOnTitleListener(OnTitleListener listener) {
        mLlTop.setOnTitleListener(listener);
    }

    public <T extends View> T findView(int id) {
        return (T) findViewById(id);
    }

    /**
     * 关闭activity，相当于销毁
     */
    public void closeActivity() {
        ScreenManager.getInstance().popActivity(this);
        overridePendingTransition(R.anim.anim_push_right_in, R.anim.anim_push_right_out);
    }

    /**
     * 显示加载框
     */
    public void showLoadingDialog() {
        showLoadingDialog(null);
    }

    /**
     * 显示加载框
     *
     * @param text 文本
     */
    public void showLoadingDialog(String text) {
        if (mLoadingDialog == null) {
            mLoadingDialog = new LoadingDialog(this);
        }

        //2个有一个show，则可以
        if (mLoadingDialog.isShowing() || mRefreshLayout.isRefreshing()) {
            return;
        }
        if (StringUtil.isNotBlank(text)) {
            mLoadingDialog.setLoadText(text);
        }
        mLoadingDialog.show();
    }

    /**
     * 显示进度条的dialog
     *
     * @param progress
     */
    public void showLoadingDialog(int progress) {
        if (mLoadingDialog == null) {
            mLoadingDialog = new LoadingDialog(this);
        }
        mLoadingDialog.setProgress(progress);
        if (mLoadingDialog.isShowing()) {
            return;
        }
        mLoadingDialog.show();
    }

    /**
     * 隐藏加载框
     */
    public void hideLoadingDialog() {
        if (mRefreshLayout.isRefreshing()) {
            mRefreshLayout.setRefreshing(false);
        }
        if (mLoadingDialog == null) {
            return;
        }
        if (mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        onBackClick();
    }

    /**
     * 注册EventBus
     */
    public void registerEventBus() {
        EventBusUtil.register(this);
    }

    /**
     * 校验是否登录，若没有跳转到登录界面
     */
    public boolean isLogin() {
        if (XYJApplication.getUserInfo() == null) {
            IntentManager.getInstance().goLoginActivity(mContext);
            return false;
        } else {
            return true;
        }
    }

    /**
     * 注销EventBus
     */
    public void unRegisterEventBus() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }


//    /**
//     * 界面是否在前台
//     *
//     * @param context
//     * @param className
//     * @return
//     */
//    protected boolean isForeground(Context context, String className) {
//        if (context == null || TextUtils.isEmpty(className)) {
//            return false;
//        }
//        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
//        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
//        if (list != null && list.size() > 0) {
//            ComponentName cpn = list.get(0).topActivity;
//            Log.d("Debug", cpn.getClassName());
//            if (className.equals(cpn.getClassName())) {
//                return true;
//            }
//        }
//        return false;
//    }

    /**
     * 用于Http请求的监听器
     */
    public abstract class MyHttpResponseListener extends HttpResponseListener {

        @Override
        public void onStart() {
            if (!isLoadingAnimShow)
                showLoadingDialog();
            showNetErrorView(false);
        }

        @Override
        public void onFail(String msg) {
            hideLoadingDialog();
            if (StringUtil.isNotBlank(msg)) {
                ToastUtil.show(msg);
            }
            if (isLoadingAnimShow) {
                setLoadingAnimVisible(false);//异常加载动画 不可见
            }
        }

        @Override
        public void onSuccess(Object model) {
            hideLoadingDialog();
        }

        @Override
        public void onDone(String msg) {
            hideLoadingDialog();
            if (isLoadingAnimShow) {
                setLoadingAnimVisible(false);//异常加载动画 不可见
            }
            if (StringUtil.isNotBlank(msg)) {
                ToastUtil.show(msg);
            }
            showNetErrorView(true);
        }

        @Override
        public void onError() {
            hideLoadingDialog();
            ToastUtil.show(getResources().getString(R.string.tip_net_error));
            if (isLoadingAnimShow) {
                setLoadingAnimVisible(false);//异常加载动画 不可见
            }
            showNetErrorView(true);
        }
    }
}
